package cz.data.auth.security;

import cz.data.auth.service.SecurityService;
import cz.data.common.core.DataConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

public class NacosServiceAuthenticationFilter extends OncePerRequestFilter {

    private final SecurityService securityService;

    public NacosServiceAuthenticationFilter(SecurityService securityService) {
        this.securityService = securityService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorization = request.getHeader(DataConstant.Token.SERVICE_HEADER);
        if (StringUtils.isNotBlank(authorization) && authorization.startsWith("Basic ")) {
            try {
                boolean auth = securityService.serviceAuth(authorization);
                if (auth) {
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authorization, null, Collections.emptyList());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            } catch (Exception ignored) {

            }
        }
        filterChain.doFilter(request, response);
    }
}
